%{
AUTHOR: Felipe Arteaga
-------------------------------------------------------------------------
PROJECT: Warnings
-------------------------------------------------------------------------
DESCRIPTION:
=========================================================================
%}


clearvars -except projectDir projectDirData fromMainWarningsPaper
clc;close all;fclose('all');feature('DefaultCharacterSet','UTF-8');

if(not(exist('projectDir','var')==1&&exist('projectDirData','var')==1&&exist('fromMainWarningsPaper','var')==1&&fromMainWarningsPaper))
    pcName=char(java.lang.System.getProperty('user.name'));
    if(strcmp(pcName,'felipe'))
        % PC Felipe
        myDir='/Users/felipe/Dropbox/';
        projectDir=[myDir,'git/warnings/'];
        projectDirData=[myDir,'projects/warnings/'];
        addpath(genpath([myDir,'/myMatlabFunctions/']));
    end
end
compileLatexTable=false;

%%

%warning('Alternative dir plots')
dirPlots=[projectDir,'/paper/figuresCL/other/'];

dirData=[projectDirData,'/data/chile/'];
dirDataAux=[projectDirData,'/data/chile/auxiliar/'];


tableBandwidthComparison=false;
plotRDs=true;
titlePlotRD=true;
plotWithZoom=false;
savePlotRDs=true;
bandwidthTable='local'; % 'full','local','localAuto';

switch bandwidthTable
    case 'full'
        bwnote='Full bandwidth was used (-0.28,+0.68) with 2nd order (local) polynomial fit. ';
    case 'local'
        bwnote='Bandwidth was set to +-0.1 with default local polynomial fit (1st order). ';
    case 'localAuto'
        bwnote='Bandwidth was set to automatic (bwselect with default options) with default polynomial fit (1st order). ';
end


% For making subfigures with plots:
maxHorzPlots=3;
maxVertPlots=4;

%% Load data:
anho=0; %0: pooled
if(anho==0)
    anhoStr='';
else
    anhoStr=sprintf('%i',anho);
end


notIn2020={}; % {'assignedToPref','acceptOffer','declineOffer','preferenciaAsign_1','placedInAnyPreferenceIniEnd','placedInAddedIniEnd','placedInAddedNoWaitlistIniEnd','placedInOldIniEnd','enrolledInAssigned','enrolledInAddedIniEnd','enrolledInAddedNoWaitlistIniEnd','enrolledInAddedNoRiskIniEnd'};


if(anho==0)
    
    d1=load([dirData,'2018/inputRD'],'dataRD');
    d2=load([dirData,'2019/inputRD'],'dataRD');
    d3=load([dirData,'2020/inputRD'],'dataRD');
    % Variables that are not available for 2020 yet:
    fillWithNan=notIn2020;
    %fillWithNan=
    for v=1:length(fillWithNan)
        d3.dataRD.(fillWithNan{v})=nan(height(d3.dataRD),1);
    end
    
    
    % Universe that is comparable between 2018-2020
    entryGrades=[-1 0 1 7 9];
    sirven1=ismember(d1.dataRD.grade,entryGrades)&not(d1.dataRD.cod_reg==13);
    sirven2=ismember(d2.dataRD.grade,entryGrades)&not(d2.dataRD.cod_reg==13);
    sirven3=ismember(d3.dataRD.grade,entryGrades)&not(d3.dataRD.cod_reg==13);
    
    d1.dataRD.comparable=sirven1;
    d2.dataRD.comparable=sirven2;
    d3.dataRD.comparable=sirven3;
    
    d1.dataRD.anho=2018*ones(height(d1.dataRD),1);
    d2.dataRD.anho=2019*ones(height(d2.dataRD),1);
    d3.dataRD.anho=2020*ones(height(d3.dataRD),1);
    
    % Keep vars in common
    
    incommon=intersect(intersect(d1.dataRD.Properties.VariableNames,d2.dataRD.Properties.VariableNames),d3.dataRD.Properties.VariableNames);
    incommon=incommon(not(strcmp(incommon,'mrun')));
    dataRD=[d1.dataRD(:,incommon);d2.dataRD(:,incommon);d3.dataRD(:,incommon)];
    
    
    
else
    load([dirData,anhoStr,'/inputRD'],'dataRD')
end

dataRD.rural=dataRD.newMarket<0;

% As asignment at .3 is control, just move (if any) in .3 to epsilon to the
% left:
dataRD.riskPopup(dataRD.riskPopup==.3)=.29999999;

% Avoid mass points at extremes:
dataRD.restrAll=dataRD.pobPopup==1&dataRD.riskPopup>.02&dataRD.riskPopup<.98;

% No need to be more specific, and put "Predicted placement risk of 1st
% attempt"
dataRD.Properties.VariableDescriptions{'riskPopup'}='Predicted placement risk';
dataRD.Properties.VariableDescriptions{'treatedPopup'}='Treated pop-up in first attempt';


% La hago de nuevo, pq no está la var pal 2020
dataRD.enrolledInAssigned=dataRD.rbdEnrolled==dataRD.rbdAsign_1&dataRD.assignedToPref;% Importante el ultimo pa sacar los matricula asegurada

%% Genero un contrafactual para los que se les obligo a agregar

% not(dataRD.appLength1Erased)
% Postula a 2, primer rbd no es unico en comuna
% No es postulante voluntario

% Load data
noVol=table;
unicoEnComuna=table;

load([dirDataAux,'/unicosEnComunaYNoVolunatarios2018'])
noVol.idPostulante=idsNoVoluntarios;
noVol.anho=scalarForTable(2018,noVol);
unicoEnComuna.rbd=unicosEnComuna;
unicoEnComuna.anho=scalarForTable(2018,unicoEnComuna);
clearvars unicosEnComuna idsNoVoluntarios

noVol_=table;
unicoEnComuna_=table;
load([dirDataAux,'/unicosEnComunaYNoVolunatarios2019'])
noVol_.idPostulante=idsNoVoluntarios;
noVol_.anho=scalarForTable(2019,noVol_);
unicoEnComuna_.rbd=unicosEnComuna;
unicoEnComuna_.anho=scalarForTable(2019,unicoEnComuna_);
noVol=[noVol;noVol_];
unicoEnComuna=[unicoEnComuna;unicoEnComuna_];
clearvars unicosEnComuna idsNoVoluntarios

noVol_=table;
unicoEnComuna_=table;
load([dirDataAux,'/unicosEnComunaYNoVolunatarios2020'])
noVol_.idPostulante=idsNoVoluntarios;
noVol_.anho=scalarForTable(2020,noVol_);
unicoEnComuna_.rbd=unicosEnComuna;
unicoEnComuna_.anho=scalarForTable(2020,unicoEnComuna_);
noVol=[noVol;noVol_];
unicoEnComuna=[unicoEnComuna;unicoEnComuna_];
clearvars unicosEnComuna idsNoVoluntarios

dataRD.primerRbdUnicoEnComuna=ismember([dataRD.rbd_firstIni,dataRD.anho],[unicoEnComuna.rbd,unicoEnComuna.anho],'rows');

%{
Mandatory (added one): Applied to 1 in first attempt, first school is in
"big urban zone", is obligated to add at least 1 schools. Added only one.

Mandatory (added>1): Applied to 1 in first attempt, first school is in
"big urban zone", is obligated to add at least 1 schools. Added more than
one.

Applied 2: Applied to 2 in first attempt, didn't add any schools. First school is in
"big urban zone"

Allowed 1, non risky and added: Applied to 1 in first attempt, added more schools. First school is not in "big
urban zone" (that's why he could apply to one). NO POP-UP WARNING
(potentailly SMS warning though)

Allowed 1, risky and added: Applied to 1, add more schools. First school is not in "big
urban zone" (that's why he could apply to one). WITH POP-UP WARNING

%}

dataRD.contrafactualCris=not(dataRD.primerRbdUnicoEnComuna)&...
    not(dataRD.appLength1Erased)&...
    dataRD.lengthIni==2&dataRD.lengthEnd==2&...
    not(dataRD.voluntary);

dataRD.obligados=dataRD.appLength1Erased&...
    dataRD.lengthIni==2&dataRD.lengthEnd==2;

dataRD.obligados2=dataRD.appLength1Erased&not(dataRD.obligados);

dataRD.contrafactualPostularonSolos= dataRD.lengthIni==1&dataRD.lengthEnd>1&...
    not(dataRD.voluntary)&not(dataRD.treatedPopup);

dataRD.contrafactualPostularonWarning=dataRD.lengthIni==1&dataRD.lengthEnd>1&...
    not(dataRD.voluntary)&dataRD.treatedPopup;

dataRD.status=scalarForTable(nan,dataRD);

dataRD.status(dataRD.obligados)=1;
%dataRD.status(dataRD.obligados2)=0;
dataRD.status(dataRD.contrafactualCris)=2;
%dataRD.status(dataRD.contrafactualPostularonSolos)=3;
%dataRD.status(dataRD.contrafactualPostularonWarning)=4;
dataRD.status=categorical(dataRD.status,[0 1 2 3 4],{'Mandatory (added$>$1)','Required to add second choice','Applied voluntarily','Allowed 1, non risky and added','Allowed 1, risky and added'});

dataRD.status=removecats(dataRD.status);
close all

outcome={'declineOffer','Declined'};
outcome={'enrolledInAssigned','Enrolled'};
% 
% figure
% barmean(dataRD,'status',outcome{1},'all',0)
% easyExport('','height',300)
% 
% figure
 br1st=barmean(dataRD(dataRD.preferenciaAsign_1==1,:),'status',outcome{1},'all',0);
% title('Reject conditional on assigned to 1st')
% easyExport(dirBasura('reject1'),'height',300)
% 
% figure
 br2nd=barmean(dataRD(dataRD.preferenciaAsign_1==2,:),'status',outcome{1},'all',0);
% title('Reject conditional on assigned to 2nd')
% easyExport(dirBasura('reject2'),'height',300)

%% Ambos en un solo plot

matriz=[br1st.height, br2nd.height];
figure
b=bar(categorical(categories(dataRD.status)),matriz,'facealpha',.6);


x1=b(1).XEndPoints;
x2=b(2).XEndPoints;

colors=linspecer(2);
hold on
errorbar(x1,br1st.height,br1st.radioInterval,'lineStyle','none','color',colors(2,:))
errorbar(x2,br2nd.height,br2nd.radioInterval,'lineStyle','none','color',colors(2,:))
hold off

dummyPrecision='%3.1f$\\%%$';
for i=1:size(matriz,1)
    
annotation2('textbox',[x1(i),br1st.height(i)/2],'o','String',sprintf(dummyPrecision,br1st.height(i)*100),'Interpreter','latex','edgecolor','none','color',[0 0 0]);
annotation2('textbox',[x2(i),br2nd.height(i)/2],'o','String',sprintf(dummyPrecision,br2nd.height(i)*100),'Interpreter','latex','edgecolor','none','color',[0 0 0]);
            
end

ylim([0,1.1])
legend({[outcome{2},'|placed in 1st'],[outcome{2},'|placed in 2nd']},'Interpreter','latex')
easyExport([dirPlots,'/enrolledPlacement.png'],'width',400,'height',300)





